package cn.nawang.ebeim.client.util;


import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName: RunningDsIds
 * @Description: 备份中的DsId
 * @author 张建峰
 * @date 2015年8月24日 下午4:10:17
 * @version v1.0
 * 
 *          修改时间，2015年9月9日09:14:14
 */
public class RunningDsIds {
    public interface CurrentExitsDsId {
        public String findId(String id);
    }

    private static Set<String> runingDsIds = new HashSet<String>();

    private static CurrentExitsDsId currentExitsDsId;


    public static CurrentExitsDsId getCheckExitsDsId() {
        return currentExitsDsId;
    }

    public static void setCheckExitsDsId(CurrentExitsDsId currentExitsDsId) {
        RunningDsIds.currentExitsDsId = currentExitsDsId;
    }

    public static void addId(String id) {
        synchronized (runingDsIds) {
            runingDsIds.add(id);
        }
    }

    public static Set<String> executeIterator() {
        synchronized (runingDsIds) {
            Iterator<String> it = runingDsIds.iterator();
            Set<String> ids = new HashSet<String>();
            while (it.hasNext()) {
                String id = currentExitsDsId.findId(it.next());
                if(id!=null){
                    ids.add(id);
                }
            }
            return ids;
        }
    }

    public static void remove(Set<String> removeSet) {
        synchronized (runingDsIds) {
            runingDsIds.removeAll(removeSet);
        }
    }


    public static void main(String[] args) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                int i = 0;
                while (true) {
                    RunningDsIds.addId(++i + "");
                    if (i % 8 == 0) {
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                setCheckExitsDsId(new CurrentExitsDsId() {

                    @Override
                    public String findId(String id) {
//                        System.out.println(id);
                        try {
                            Thread.sleep(30);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return id;
                    }
                });
                while (true) {
                    Set<String> ids = executeIterator();
                    remove(ids);
                }
            }
        }).start();
    }

}
